const fs = require("fs");
const path = require('path')
const axios = require('axios');
const pageUrl = 'pages.json';
const listName = ['AllList', 'YBList', 'UnitList'];

//端口号
const api = "http://192.10.49.41:8000"
//站点id
const data = {
	key: "d0129553-57ce-48ed-88a0-493f91e2e21f"
};

const port = "/api/Menu/GetInfoByPhone";
const PhoneCinfigUrl = api + port;


function getData() {

	//获取平台配置移动端数据
	const p1 = getToken().then(res => {
		return getPhoneData(res.Token);
	})


	//读取pages.js数据
	const p2 = readPagesJs();

	Promise.all([p1, p2]).then(([phoneData, pagesData]) => {

		const pData = {
			...pagesData
		};

		phoneData.forEach(item => {

			pData.pages.push({
				path: item.PhoneUrl,
				style: {
					h5: {
						"navigationBarTitleText": item.PhoneColor,
						"titleNView": false
					}
				}
			})

			let arr = item.PhoneUrl.split('/');
			let end = arr.slice(-1)[0];
			let name = end + '.vue';
			arr.pop();
			let path = arr.join("/");
			let formUrl = "";
			listName.forEach(item => {
				if (end.includes(item)) {
					formUrl = "/" + path + '/' + end.split(item)[0] + 'Form';
				}
			})

			const modelStr = getModelStr('list', item.MenuContent, formUrl)
			//创建vue文件
			writeAFile(path, name, modelStr);
		})


		const clist = deWeightArray(pData.pages, "path");
		pData.pages = clist;

		fs.writeFile(pageUrl, JSON.stringify(pData), (err) => {
			if (err) {
				console.log(pageUrl + " 出错了", err);
			} else {
				console.log(pageUrl + " 写入成功");
			}
		});


	})

}


function getToken() {
	return new Promise((resolve, reject) => {
		axios.post("http://192.10.49.41:8000/api/Login/CheckLogin", {
			UserCode: "8a2baf2bfd25729693ca1e361b561772",
			W: "2a0a0fa9200c6b3c0d6eced809493903",
			Key: "752CC05B"
		}).then(res => {
			if (res.status == 200) {
				resolve(res.data);
			}
		})
	})
}

function getPhoneData(token) {
	return new Promise((resolve, reject) => {
		axios.post(PhoneCinfigUrl, data, {
			headers: {
				Authorization: `${token}`
			}
		}).then(res => {
			if (res.status == 200) {
				resolve(res.data);
			}
		})
	})
}


function readPagesJs() {
	return new Promise((resolve, reject) => {
		fs.readFile(pageUrl, (err, pagesData) => {
			if (err) {
				reject(err);
			} else {
				resolve(JSON.parse(pagesData));
			}
		})
	})
}


// data 是新文件的内容，字符串 
// suffix 文件后缀名
// preUrl 文件路径
function writeAFile(preUrl, name, data) {

	let _path = preUrl + '/' + name;
	let str = data;
	return new Promise((resolve, reject) => {
		fs.mkdir(path.resolve('./' + preUrl), {
			recursive: true
		}, (err) => {
			if (err) {
				resolve(err)
			} else {
				fs.writeFile('./' + _path, str, function(err) {
					if (err) {
						console.log(name + ' 写入文件失败:', err);
					} else {
						console.log(name + ' 写入文件成功');
					}
					resolve(err)
				})
			}
		})
	})
}


//去重 arr:数据源、ItemName：去重条件
let deWeightArray = (arr, ItemName) => {
	let map = new Map();
	for (let item of arr) {
		if (!map.has(item[ItemName])) {
			map.set(item[ItemName], item);
		}
	}
	return [...map.values()];
}


getData();




function getModelStr(type, listCode, formUrl) {
	let listStr = "";
	if (type == "list") {
		listStr = `
<template>
	<view>
		<view class="search_fixed">
			<mySearch :columnList="columnList" @SearchEvent="SearchEvent" @ClearEvent="ClearEvent"></mySearch>
		</view>
	
		<mescroll-body @init="mescrollInit" @down="downCallback" :down="$gl.downOption" @up="upCallback"
			:up="$gl.upOption" :top="$gl.upOption.top">
			<myGroupItem :dataList="list" :columnList="columnList" @toPage="toPage"></myGroupItem>
		</mescroll-body>
	
	</view>
</template>
<script>
	export default {
		data() {
			return {
				list: [],
				columnList: [],
				filter: {
					"list": []
				},
				listCode: "` + listCode + `",
				api: "",
				formUrl: "` + formUrl + `"
			}
		},
		onReady() {
			this.$gl.getColumn(this).then(res => {
				this.api = res
				this.mescroll.triggerUpScroll();
			})
		},
		methods: {
			upCallback(page) {
				this.loadData(page.num, page.size)
			},
			loadData(index, size, obj = {}) {
				this.$gl.loadMore(this, index, size, obj);
			},
			SearchEvent(e) {
				this.list = [];
				this.filter = e;
				this.mescroll.resetUpScroll()
			},
			ClearEvent(e) {
				this.list = [];
				this.filter.list = [];
				this.mescroll.resetUpScroll()
			},
			toPage(e) {
				this.$gl.setStorage({
					action: "view",
					Key: e.BDBM,
					Run_ID: e.Run_ID ?? "",
					Step_Handler_ID: e.Step_Handler_ID ?? ""
				}, this.formUrl);
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>
`
	}

	return listStr
}
